package server

import (
	"file-cleaner/internal/file_cleaner/clean_handler"
	"file-cleaner/internal/file_cleaner/report"
	"runtime"
	"sync"
	"time"
)

type Server struct {
	FileCleanerApi
	Reporter       report.Reporter
	TaskInfoCache  *clean_handler.CleanTaskInfoCache
	gcCycle        time.Duration
	queryBaseDir   string
	queryExcludes  []string
	isCascadeQuery bool
}

func (s *Server) Start() error {
	// Active GC mechanism
	if s.gcCycle >= time.Second && s.gcCycle < time.Minute*2 {
		gcgoWG := new(sync.WaitGroup)
		gcDone := make(chan interface{}, 0)
		gcgoWG.Add(1)
		go func() {
			ticker := time.NewTicker(s.gcCycle)
			for true {
				select {
				case <-ticker.C:
					runtime.GC()
				case <-gcDone:
					gcgoWG.Done()
					close(gcDone)
					return
				}
			}
		}()
		defer gcgoWG.Wait()
		defer func() { gcDone <- 9 }()
	}

	// Setup and start the file cleaner api
	err := s.FileCleanerApi.Run()
	if err != nil {
		return err
	}

	// Files query start
	err = s.FileCleanerApi.Query(s.queryBaseDir, s.isCascadeQuery, s.queryExcludes)
	if err != nil {
		return err
	}

	// Waiting for the task to be completed
	s.FileCleanerApi.Done()

	return nil
}
